const os = require('os');
const fs = require('fs');
const { exec } = require('child_process');
const { domain } = require('./domain.json')

const COMPACT_REGEXP = /\s+/g;
const compact = (str) => str.replace(COMPACT_REGEXP, ' ');
const myexec = (command) => {
    return new Promise((resolve, reject) => {
        exec(compact(command), (err, stdout, stderr) => {
          if (err) reject(err);
          else if (stderr) reject(stderr);
          else resolve(stdout);
        });
    })
}

const startToPush = (address) => {
    const newDomain = {
        domain: address
    }
    console.log(address)
    
    fs.writeFileSync('domain.json', JSON.stringify(newDomain));
    console.log('write file success')
    
    myexec(`git add .`)
        .then(v => {
            console.log('git add .');
            return exec(`git commit -m "${address}"`)
        }).then(v => {
            console.log(`git commit -m "${address}"`);
            return exec('git push')    
        }).then(v => {
            console.log(`git push`);
    
        })
}

const getDomain = () => {
    const ips = os.networkInterfaces()

    const wlan = ips['pppoe-wan']
    if (!wlan) {
        return null;
    }

    const ipV4 = wlan.find(v => v.family === 'IPv4')
    // if(!ipV4 || domain === ipV4.address) {
    //     console.log('stop')
    //     return null;
    // }
    return ipV4.address

}

const job = () => {
    const address = getDomain()
    if (!address) {
        return;
    }
    startToPush(address)
}

job();